package com.member.shop.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.member.common.core.domain.model.LoginUser;
import com.member.common.enums.*;
import com.member.common.exception.ServiceException;
import com.member.common.utils.DateUtils;
import com.member.common.utils.OrderNoCreate;
import com.member.common.utils.SecurityUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.bean.BeanUtils;
import com.member.common.utils.fy.HttpUtil;
import com.member.common.utils.fy.SignatureUtils;
import com.member.shop.domain.*;
import com.member.shop.dto.*;
import com.member.shop.mapper.*;
import com.member.shop.service.*;
import com.member.shop.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.redisson.api.RDelayedQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 *
 * @author lixinchen
 * @date 2024-01-08
 */
@Slf4j
@Service
public class SysBizOrderServiceImpl extends ServiceImpl<SysBizOrderMapper, SysBizOrder> implements ISysBizOrderService {
    @Resource
    private SysBizOrderMapper sysBizOrderMapper;
    @Resource
    private ISysBizUserService sysBizUserService;
    @Resource
    private ISysBizUserAddressService sysBizUserAddressService;
    @Resource
    private ISysBizGoodsService sysBizGoodsService;
    @Resource
    private ISysBizGoodsSkuService sysBizGoodsSkuService;
    @Resource
    private ISysBizOrderGoodsService sysBizOrderGoodsService;
    @Resource
    private RDelayedQueue<String> delayedQueue;
    @Resource
    private ISysBizCouponGoodsUserService sysBizCouponGoodsUserService;
    @Resource
    private ISysBizCouponReceiveService sysBizCouponReceiveService;
    @Resource
    private IPayService payService;
    @Resource
    private ISysBizUserSurplusDetailsService sysBizUserSurplusDetailsService;
    @Resource
    private SysBizOrderGoodsMapper sysBizOrderGoodsMapper;
    @Resource
    private ISysBizOrderServiceService sysBizOrderServiceService;
    @Resource
    private IAlipayService alipayService;
    @Resource
    private SysBizImportFailMapper sysBizImportFailMapper;
    @Resource
    private SysBizShopCertificationMapper sysBizShopCertificationMapper;
    @Resource
    private SysBizCouponGoodsMapper sysBizCouponGoodsMapper;

    @Value("${mall.order.privateKey}")
    private String privateKey;

    @Value("${mall.order.pushUrl}")
    private String url;

    @Value("${mall.order.cancelUrl}")
    private String cancelUrl;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public SysBizOrder selectSysBizOrderById(Long id) {
        return sysBizOrderMapper.selectById(id);
    }

    /**
     * 查询订单列表
     *
     * @param queryWrapper 订单
     * @return 订单
     */
    @Override
    public List<SysBizOrder> selectSysBizOrderList(LambdaQueryWrapper<SysBizOrder> queryWrapper) {
        return sysBizOrderMapper.selectList(queryWrapper);
    }

    /**
     * 查询订单列表
     *
     * @param sysBizOrder 订单
     * @return 订单
     */
    @Override
    public List<SysBizOrder> selectSysBizOrderList(SysBizOrder sysBizOrder) {
        List<SysBizOrder> sysBizOrders = sysBizOrderMapper.selectSysBizOrderList(sysBizOrder);
//        if (!CollectionUtils.isEmpty(sysBizOrders)) {
//            for (SysBizOrder bizOrder : sysBizOrders) {
//                SysBizUser sysBizUser = sysBizUserService.getById(bizOrder.getUserId());
//                if (sysBizUser != null) {
////                    bizOrder.setUserName(sysBizUser.getFullName());
////                    bizOrder.setPhone(sysBizUser.getUserPhone());
//                }
//                sysBizOrder.setAddress(sysBizOrder.getReceiverAddress());
//            }
//        }
        return sysBizOrders;
    }

    /**
     * 新增订单
     *
     * @param sysBizOrder 订单
     * @return 结果
     */
    @Override
    public int insertSysBizOrder(SysBizOrder sysBizOrder) {
        sysBizOrder.setCreateTime(DateUtils.getNowDate());
        return sysBizOrderMapper.insert(sysBizOrder);
    }

    /**
     * 修改订单
     *
     * @param sysBizOrder 订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PrintOrderDto updateSysBizOrder(SysBizOrder sysBizOrder) {
        sysBizOrder.setDeliveryGoodsTime(DateUtils.getNowDate());
        sysBizOrder.setUpdateTime(DateUtils.getNowDate());
        sysBizOrder.setStatus(OrderSatusEnum.TO_BE_RECEIVED.getKey());
        sysBizOrder.setExpressCompany("德邦快递");

        PrintOrderDto printOrderDto = new PrintOrderDto();
        if (sysBizOrder.getId() == null) {
            LambdaQueryWrapper<SysBizOrder> sysBizOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysBizOrderLambdaQueryWrapper.eq(SysBizOrder::getOrderCode, sysBizOrder.getOrderCode());
            SysBizOrder sysBizOrder1 = sysBizOrderMapper.selectOne(sysBizOrderLambdaQueryWrapper);
            if (sysBizOrder1 == null) {
                throw new ServiceException("订单编号输入错误" + sysBizOrder.getOrderCode());
            }
            sysBizOrder.setId(sysBizOrder1.getId());
        }
        //订单详情
        SysBizOrder sysBizOrder1 = sysBizOrderMapper.selectSysBizOrderById(sysBizOrder.getId());
        //订单商品
        List<SysBizOrderGoods> sysBizOrderGoods = sysBizOrderGoodsMapper.selectList(new LambdaQueryWrapper<SysBizOrderGoods>().eq(SysBizOrderGoods::getOrderId, sysBizOrder1.getId()));


        debangOrder debangOrder = new debangOrder();
        debangOrder.setCompanyCode("EWBGZAMGJK");
        debangOrder.setCustOrderNo(sysBizOrder1.getOrderCode());
        debangOrder.setCustomerCode("875916415");
        debangOrder.setLogisticID("ACMK" + sysBizOrder1.getOrderCode());
        debangOrder.setNeedTraceInfo(1);
        debangOrder.setOrderType("3");

        debangPackageInfo debangPackageInfo = new debangPackageInfo();
        debangPackageInfo.setCargoName("货物");
        debangPackageInfo.setDeliveryType("4");
        debangPackageInfo.setTotalNumber(1);
//        debangPackageInfo.setTotalVolume(10.00);
        debangPackageInfo.setTotalWeight(10.00);
//        debangPackageInfo.setPackageService("纤");
        debangOrder.setPackageInfo(debangPackageInfo);


        debangReceiver debangReceiver = new debangReceiver();
        debangReceiver.setAddress(sysBizOrder1.getReceiverAddress());
        debangReceiver.setCity(sysBizOrder1.getCity());
        debangReceiver.setCompanyName("德邦快递");
        debangReceiver.setCounty(sysBizOrder1.getArea());
        debangReceiver.setMobile(sysBizOrder1.getContactNumber());
        debangReceiver.setTown(sysBizOrder1.getArea());
        debangReceiver.setName(sysBizOrder1.getReceiver());
        debangReceiver.setProvince(sysBizOrder1.getProvince());
//        debangReceiver.setTown(sysBizOrder1.getArea());
        debangOrder.setReceiver(debangReceiver);

        debangSender debangSender = new debangSender();
        debangSender.setAddress("广东省广州市白云区人和镇大巷工业区21号");
        debangSender.setCity("广州市");
        debangSender.setCompanyName("德邦快递");
        debangSender.setCounty("白云区");
        debangSender.setMobile("13527754394");
        debangSender.setName("艾初美");
        debangSender.setProvince("广东省");
        debangSender.setTown("人和镇大巷工业区21号");
        debangOrder.setSender(debangSender);
        debangOrder.setTransportType("RCP");
        debangOrder.setGmtCommit(DateUtils.getTime());
        debangOrder.setPayType("1");
        debangOrder.setIsOut("N");
        String jsonString = JSONObject.toJSONString(debangOrder);
        long timestamp = System.currentTimeMillis();


//        String params = jsonString.replaceAll("@time", DateUtils.getTime());
        //getDigest(_params + 你的appkey + timestamp);
        String digest = getDigest(jsonString + "d2054e1be5019c0f508659ed5ded2733" + timestamp);
        //你的company code
        String companyCode = "EWBGZAMGJK";

        Map map = new LinkedHashMap();
        map.put("params", jsonString);
        map.put("digest", digest);
        map.put("timestamp", String.valueOf(timestamp));
        map.put("companyCode", companyCode);

        String url = "http://gwapi.deppon.com/dop-interface-async/standard-order/createOrderNotify.action";

        String response = null;
        try {
            response = HttpUtil.postForm(url, map);
            MailInfo mailInfo = JSONObject.parseObject(response, MailInfo.class);
            if ("true".equals(mailInfo.getResult())) {
                sysBizOrder.setExpressNo(mailInfo.getMailNo());
                printOrderDto.setWaybillNumber(mailInfo.getMailNo());  //运单号
//                printOrderDto.setShipperCompanyPhone();
//                printOrderDto.setShipperCompanyAddress();
                printOrderDto.setShipperTel("13527754394");  // 发货人电话
                printOrderDto.setSaddress("广东省广州市白云区人和镇大巷工业区21号");  //发货人地址
                printOrderDto.setShipperPhone("13527754394"); //发货人电话
                printOrderDto.setConPhone(sysBizOrder1.getContactNumber()); //收货人电话
                printOrderDto.setConTel(sysBizOrder1.getContactNumber());  //收货人电话
                printOrderDto.setShipperName("艾初美");  //发货人姓名
                printOrderDto.setConName(sysBizOrder1.getReceiver());   //收货人姓名
                printOrderDto.setCaddress(sysBizOrder1.getProvince() + '-' + sysBizOrder1.getCity() + '-' + sysBizOrder1.getArea() + '-' + sysBizOrder1.getReceiverAddress());  //收货地址
                printOrderDto.setCargoName1("货物");
                printOrderDto.setCargoWeight("10");
                printOrderDto.setRefundPayment("10");
                printOrderDto.setPayType("到付");
                printOrderDto.setTransType("送货上楼");
//                printOrderDto.setDestination();
//                printOrderDto.setBillWeight();
//                printOrderDto.setTransportCharge();
//                printOrderDto.setTotalCharge();
//                printOrderDto.setInsuranceMoney();
                printOrderDto.setSignSheet("无需返单");
//                printOrderDto.setOuterField1();
//                printOrderDto.setLastOutLoadOrgName();
//                printOrderDto.setDepartCityName();
//                printOrderDto.setSecondLoadOrgName();
//                printOrderDto.setStationNumber();
                printOrderDto.setCustOrderLine(mailInfo.getMailNo()); //客户订单号
                printOrderDto.setTransNote1("");
                printOrderDto.setMarkerPen1(sysBizOrder1.getRemark());
                printOrderDto.setProvince(sysBizOrder1.getProvince());
                printOrderDto.setCity(sysBizOrder1.getCity());
                printOrderDto.setCounty(sysBizOrder1.getArea());

//                printOrderDto.setOrderNumber();
//                printOrderDto.setBillTime();
//                printOrderDto.setCargoCount();
//                printOrderDto.setReciveLoanAccount();
//                printOrderDto.setPrintSerialNos();
//                printOrderDto.setIsHideWareHouse();
//                printOrderDto.setOriginalNumber();
            } else {
                throw new ServiceException("德邦提示：" + mailInfo.getReason());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        int i = sysBizOrderMapper.updateById(sysBizOrder);
        return printOrderDto;

    }

    private static String getDigest(String plainText) {
        return Base64.encodeBase64String(DigestUtils.md5Hex(plainText).getBytes());
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteSysBizOrderByIds(Long[] ids) {
        return sysBizOrderMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteSysBizOrderById(Long id) {
        return sysBizOrderMapper.deleteById(id);
    }

    /**
     * 查询订单列表(统计)
     *
     * @param sysBizOrder 订单
     * @return 订单集合
     */
    @Override
    public List<SysBizOrder> listOrderCount(SysBizOrder sysBizOrder) {
        return sysBizOrderMapper.listOrderCount(sysBizOrder);
    }

    @Override
    public String preorder(OrderDataVo dataVo, OrderPerDto orderPerDto, Long userId) {
        String dateStartToStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getNowDate()) + " 00:00:00";
        String dateEndToStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getNowDate()) + " 23:59:59";
        Date startDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, dateStartToStr);
        Date endDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, dateEndToStr);
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
        SysBizGoodsSku sysBizGoodsSku;
        if (orderPerDto.getAddressId() != null) {
            SysBizUserAddress sysBizUserAddress = sysBizUserAddressService.selectSysBizUserAddressById(orderPerDto.getAddressId());
            if (sysBizUserAddress != null) {
                dataVo.setSysBizUserAddress(sysBizUserAddress);
            }
        } else {
            List<SysBizOrder> sysBizOrders = sysBizOrderMapper.selectList(new LambdaQueryWrapper<SysBizOrder>().eq(SysBizOrder::getUserId, userId));
            if (!CollectionUtils.isEmpty(sysBizOrders)) {
                sysBizOrders.sort(Comparator.comparing(SysBizOrder::getId, Comparator.reverseOrder()));
                SysBizOrder sysBizOrder = sysBizOrders.get(0);
                SysBizUserAddress sysBizUserAddress = sysBizUserAddressService.selectSysBizUserAddressById(sysBizOrder.getAddressId());
                if (sysBizUserAddress != null) {
                    dataVo.setSysBizUserAddress(sysBizUserAddress);
                } else {
                    LambdaQueryWrapper<SysBizUserAddress> sysBizUserAddressLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    sysBizUserAddressLambdaQueryWrapper.eq(SysBizUserAddress::getStatus, 1);
                    sysBizUserAddressLambdaQueryWrapper.eq(SysBizUserAddress::getUserId, userId);
                    SysBizUserAddress userAddress = sysBizUserAddressService.getOne(sysBizUserAddressLambdaQueryWrapper);
                    if (userAddress != null) {
                        dataVo.setSysBizUserAddress(userAddress);
                    } else {
                        LambdaQueryWrapper<SysBizUserAddress> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(SysBizUserAddress::getUserId, userId);
                        List<SysBizUserAddress> list = sysBizUserAddressService.list(queryWrapper);
                        if (!CollectionUtils.isEmpty(list)) {
                            list.sort(Comparator.comparing(SysBizUserAddress::getId, Comparator.reverseOrder()));
                            SysBizUserAddress address = list.get(0);
                            dataVo.setSysBizUserAddress(address);
                        }
                    }
                }
            } else {
                LambdaQueryWrapper<SysBizUserAddress> sysBizUserAddressLambdaQueryWrapper = new LambdaQueryWrapper<>();
                sysBizUserAddressLambdaQueryWrapper.eq(SysBizUserAddress::getStatus, 1);
                sysBizUserAddressLambdaQueryWrapper.eq(SysBizUserAddress::getUserId, userId);
                SysBizUserAddress userAddress = sysBizUserAddressService.getOne(sysBizUserAddressLambdaQueryWrapper);
                if (userAddress != null) {
                    dataVo.setSysBizUserAddress(userAddress);
                } else {
                    LambdaQueryWrapper<SysBizUserAddress> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SysBizUserAddress::getUserId, userId);
                    List<SysBizUserAddress> list = sysBizUserAddressService.list(queryWrapper);
                    if (!CollectionUtils.isEmpty(list)) {
                        list.sort(Comparator.comparing(SysBizUserAddress::getId, Comparator.reverseOrder()));
                        SysBizUserAddress address = list.get(0);
                        dataVo.setSysBizUserAddress(address);
                    }
                }
            }
        }
        List<OrderGoodsVo> orderGoodsVoList = new ArrayList<>();
        BigDecimal amount = BigDecimal.ZERO;
        for (OrderGoodsDto orderGoodsDto : orderPerDto.getOrderGoodsDtoList()) {
            SysBizGoods sysBizGoods = sysBizGoodsService.getById(orderGoodsDto.getGoodsId());
            if (sysBizGoods == null || sysBizGoods.getDeleted().equals(OrderDeleteEnum.DELETE.getKey()) || sysBizGoods.getGrounding() ==  1) {
                String str = "";
                if(sysBizGoods != null){
                    str = sysBizGoods.getName();
                }
                return "商品不存在:" +str;
            }

            // 商品编号
            Long goodsId = orderGoodsDto.getGoodsId();
            // 锁的Key
            String lockKey = goodsId + "_" + orderGoodsDto.getSpecsKey();
            synchronized (lockKey.intern()) {
                // 查询商品SKU信息
                sysBizGoodsSku = sysBizGoodsSkuService.getOne(new LambdaQueryWrapper<SysBizGoodsSku>()
                        .eq(SysBizGoodsSku::getGoodsId, goodsId)
                        .eq(SysBizGoodsSku::getSpecsKey, orderGoodsDto.getSpecsKey()));
                if (sysBizGoodsSku == null) {
                    return "SKU不存在";
                }
                if (sysBizGoodsSku.getStatus() == 1) {
                    return sysBizGoodsSku.getSpecsKey() + "已下架";
                }
                if (sysBizGoods.getStock() == null
                        || sysBizGoods.getStock() - sysBizGoods.getFrozenStockCount() <= 0
                        || sysBizGoods.getStock() - sysBizGoods.getFrozenStockCount() < orderGoodsDto.getNumber() * sysBizGoodsSku.getLongUnitNumber()) {
                    return "库存不足";
                }
                BigDecimal salesPrice = BigDecimal.ZERO;
                BigDecimal marketPrice = BigDecimal.ZERO;

                if (sysBizUser != null) {
                    if (sysBizUser.getMemberGradeId() == 1) {
                        salesPrice = sysBizGoodsSku.getVip1Price();
                    }
                    if (sysBizUser.getMemberGradeId() == 2) {
                        salesPrice = sysBizGoodsSku.getVip2Price();
                    }
                    if (sysBizUser.getMemberGradeId() == 3) {
                        salesPrice = sysBizGoodsSku.getVip3Price();
                    }
                    if (sysBizUser.getMemberGradeId() == 4) {
                        salesPrice = sysBizGoodsSku.getVip4Price();
                    }
                    if (sysBizUser.getMemberGradeId() == 5) {
                        salesPrice = sysBizGoodsSku.getVip5Price();
                    }
                }
                marketPrice = sysBizGoodsSku.getMemberMarketPrice();
                orderGoodsVoList.add(OrderGoodsVo.builder().id(sysBizGoods.getId())
                        .cover(sysBizGoodsSku.getPic())
                        .goodsName(sysBizGoods.getName())
                        .marketPrice(marketPrice)
                        .salesPrice(salesPrice)
                        .number(orderGoodsDto.getNumber())
                        .specsKey(sysBizGoodsSku.getSpecsKey())
                        .skuId(sysBizGoodsSku.getId()).build());

                amount = amount.add(salesPrice.multiply(BigDecimal.valueOf(orderGoodsDto.getNumber())));

                // 查询优惠券列表
                LambdaQueryWrapper<SysBizCouponGoodsUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SysBizCouponGoodsUser::getUserId, userId);
                queryWrapper.eq(SysBizCouponGoodsUser::getGoodsId, sysBizGoods.getId());
                List<SysBizCouponGoodsUser> list = sysBizCouponGoodsUserService.list(queryWrapper);

                List<Long> receiveIdList = list.stream().map(SysBizCouponGoodsUser::getReceiveId).collect(Collectors.toList());
                List<SysBizCouponReceive> sysBizCouponReceives = sysBizCouponReceiveService.selectSysBizCouponReceiveByGoods(SysBizCouponReceive.builder()
                        .termBeginTime(startDate)
                        .status(0)
                        .termEndTime(endDate)
                        .thresholdAmount(amount)
                        .idList(receiveIdList)
                        .userId(userId).build());

                List<CouponOrderVo> couponOrderVoList = new ArrayList<>();
                for (SysBizCouponReceive sysBizCouponReceive : sysBizCouponReceives) {
                    CouponOrderVo couponOrderVo = CouponOrderVo.builder().id(sysBizCouponReceive.getId()).couponName(sysBizCouponReceive.getCouponName()).termBeginTime(sysBizCouponReceive.getTermBeginTime()).termEndTime(sysBizCouponReceive.getTermEndTime()).scopeUse(sysBizCouponReceive.getScopeUse()).discountValue(sysBizCouponReceive.getDiscountValue()).thresholdAmount(sysBizCouponReceive.getThresholdAmount()).couponDescription(sysBizCouponReceive.getCouponDescription()).build();
                    couponOrderVoList.add(couponOrderVo);
                }
                dataVo.setCouponOrderVoList(couponOrderVoList);
                if (!CollectionUtils.isEmpty(couponOrderVoList)) {
                    couponOrderVoList.sort(Comparator.comparing(CouponOrderVo::getDiscountValue, Comparator.reverseOrder()));
                    CouponOrderVo couponOrderVo = couponOrderVoList.get(0);
                    dataVo.setCouponOrderVo(couponOrderVo);
                }
            }
        }
        dataVo.setOrderGoodsVoList(orderGoodsVoList);

        // 真实支付金额
        BigDecimal amountPay = amount;
        // 优惠券优惠金额
        if (orderPerDto.getCouponId() != null) {
            SysBizCouponReceive sysBizCouponReceive = sysBizCouponReceiveService.getById(orderPerDto.getCouponId());
            amountPay = amountPay.subtract(sysBizCouponReceive.getDiscountValue());
        }

        // 新余额抵扣金额
        if (orderPerDto.getIsSurplus() == null) {
            dataVo.setIsSurplus(Boolean.FALSE);
            if (amountPay.compareTo(BigDecimal.ZERO) > 0) {
                // 判断可用余额是否大于0
                if (sysBizUser.getSurplus().compareTo(BigDecimal.ZERO) == 0) {
                    dataVo.setSurplusAmount(BigDecimal.ZERO);
                } else if (sysBizUser.getSurplus().compareTo(BigDecimal.ZERO) > 0) {
                    dataVo.setIsSurplus(Boolean.TRUE);
                    if (sysBizUser.getSurplus().compareTo(amountPay) >= 0) {
                        // 纯余额支付
                        amountPay = BigDecimal.ZERO;
                        dataVo.setSurplusAmount(amount);
                    }
                }
            } else if (amountPay.compareTo(BigDecimal.ZERO) == 0) {
                if (sysBizUser.getSurplus().compareTo(BigDecimal.ZERO) == 0) {
                    dataVo.setSurplusAmount(BigDecimal.ZERO);
                } else if (sysBizUser.getSurplus().compareTo(BigDecimal.ZERO) > 0) {
                    dataVo.setIsSurplus(Boolean.TRUE);
                    if (sysBizUser.getSurplus().compareTo(amount) >= 0) {
                        // 纯余额支付
                        amountPay = BigDecimal.ZERO;
                        dataVo.setSurplusAmount(amount);
                    }
                }
            }
        } else if (orderPerDto.getIsSurplus()) {
            if (sysBizUser.getSurplus().compareTo(amount) >= 0) {
                amountPay = BigDecimal.ZERO;
                // 纯余额支付
                dataVo.setSurplusAmount(amountPay);
            }
        } else {
            dataVo.setSurplusAmount(BigDecimal.ZERO);
        }

        dataVo.setTotalAmount(amount);
        dataVo.setAmount(amountPay);
        return StringUtils.EMPTY;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public String preorderNew(SysBizOrder sysBizOrder, OrderPerDto orderPerDto, Long userId, Long tenantId, PayVo payVo) {
        Date nowDate = DateUtils.getNowDate();
        long time = nowDate.getTime();
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
        SysBizGoodsSku sysBizGoodsSku;
        SysBizUserAddress sysBizUserAddress = sysBizUserAddressService.selectSysBizUserAddressById(orderPerDto.getAddressId());
        sysBizOrder.setCreateTime(nowDate);
        sysBizOrder.setTenantId(tenantId);
        sysBizOrder.setCreateBy(sysBizUser.getNickName());
        sysBizOrder.setAddressId(orderPerDto.getAddressId());
        sysBizOrder.setDelStatus(OrderDeleteEnum.NOT_DELETE.getKey());
        sysBizOrder.setContactNumber(sysBizUserAddress.getPhone());
        sysBizOrder.setCity(sysBizUserAddress.getCity());
        sysBizOrder.setArea(sysBizUserAddress.getArea());
        sysBizOrder.setProvince(sysBizUserAddress.getProvince());
        sysBizOrder.setReceiverAddress(sysBizUserAddress.getDetails());

        sysBizOrder.setStreet(sysBizUserAddress.getStreet());
        sysBizOrder.setHouseNum(sysBizUserAddress.getHouseNum());
        sysBizOrder.setLat(sysBizUserAddress.getLat());
        sysBizOrder.setLng(sysBizUserAddress.getLng());
        sysBizOrder.setReceiver(sysBizUserAddress.getName());
        sysBizOrder.setContactNumber(sysBizUserAddress.getPhone());
        sysBizOrder.setUserId(userId);
        sysBizOrder.setUserName(sysBizUser.getNickName());
        sysBizOrder.setRemark(orderPerDto.getRemark());
        BigDecimal amount = BigDecimal.ZERO;
        List<SysBizOrderGoods> sysBizOrderGoodsList = new ArrayList<>();
        for (OrderGoodsDto orderGoodsDto : orderPerDto.getOrderGoodsDtoList()) {
            SysBizGoods sysBizGoods = sysBizGoodsService.getById(orderGoodsDto.getGoodsId());
            if (sysBizGoods == null || sysBizGoods.getDeleted().equals(OrderDeleteEnum.DELETE.getKey()) || sysBizGoods.getGrounding() ==  1) {
                String str = "";
                if(sysBizGoods != null){
                    str = sysBizGoods.getName();
                }
                return "商品不存在:" +str;
            }
            // 商品编号
            Long goodsId = orderGoodsDto.getGoodsId();
            // 锁的Key
            String lockKey = goodsId + "_" + orderGoodsDto.getSpecsKey();
            // 判断价格
            BigDecimal price = null;
            synchronized (lockKey.intern()) {
                // 查询商品SKU信息
                sysBizGoodsSku = sysBizGoodsSkuService.getOne(new LambdaQueryWrapper<SysBizGoodsSku>()
                        .eq(SysBizGoodsSku::getGoodsId, goodsId)
                        .eq(SysBizGoodsSku::getSpecsKey, orderGoodsDto.getSpecsKey())
                        .eq(SysBizGoodsSku::getStatus, OrderDeleteEnum.NOT_DELETE.getKey()));
                // 如果标签不为空就用活动价格
                if(sysBizGoodsSku.getTag() != null){
                    price = sysBizGoodsSku.getActivityPrice();

                } else if (sysBizUser != null) {
                    if (sysBizUser.getMemberGradeId() == 1) {
                        price = sysBizGoodsSku.getVip1Price();
                    }
                    if (sysBizUser.getMemberGradeId() == 2) {
                        price = sysBizGoodsSku.getVip2Price();
                    }
                    if (sysBizUser.getMemberGradeId() == 3) {
                        price = sysBizGoodsSku.getVip3Price();
                    }
                    if (sysBizUser.getMemberGradeId() == 4) {
                        price = sysBizGoodsSku.getVip4Price();
                    }
                    if (sysBizUser.getMemberGradeId() == 5) {
                        price = sysBizGoodsSku.getVip5Price();
                    }
                }
                if (sysBizGoodsSku == null) {
                    return "SKU不存在";
                }
                if (sysBizGoodsSku.getStatus() == 1) {
                    return sysBizGoodsSku.getSpecsKey() + "已下架";
                }
                if (sysBizGoods.getStock() == null
                        || sysBizGoods.getStock() - sysBizGoods.getFrozenStockCount() <= 0
                        || sysBizGoods.getStock() - sysBizGoods.getFrozenStockCount() < orderGoodsDto.getNumber() * sysBizGoodsSku.getLongUnitNumber()) {
                    return "库存不足";
                }

                if (price != null) {
                    amount = amount.add(price.multiply(BigDecimal.valueOf(orderGoodsDto.getNumber())));
                }
                // 锁定 sys_biz_goods表 库存
                int stocksLock = sysBizGoodsService.lockStocks(sysBizGoods.getId(), orderGoodsDto.getNumber());
                if (stocksLock <= 0) {
                    return "库存不足";
                }
            }
            sysBizGoodsService.update(new LambdaUpdateWrapper<SysBizGoods>()
                    .set(SysBizGoods::getRealitySales, sysBizGoods.getRealitySales() + orderGoodsDto.getNumber())
                    .eq(SysBizGoods::getId, orderGoodsDto.getGoodsId()));

            BigDecimal totalAmount = BigDecimal.ZERO;
            BigDecimal marketPrice = null;

            if (price != null) {
                totalAmount = price.multiply(BigDecimal.valueOf(orderGoodsDto.getNumber()));
            }

            sysBizOrderGoodsList.add(SysBizOrderGoods.builder()
                    .createTime(nowDate)
                    .goodsName(sysBizGoods.getName())
                    .createBy(sysBizUser.getNickName())
                    .delStatus(OrderDeleteEnum.NOT_DELETE.getKey())
                    .goodsId(orderGoodsDto.getGoodsId())
                    .number(orderGoodsDto.getNumber())
                    .skuId(sysBizGoodsSku.getId())
                    .erpProductCode(sysBizGoodsSku.getErpProductCode())
                    .erpSmallUnit(sysBizGoodsSku.getErpSmallUnit())
                    .skuPic(sysBizGoodsSku.getPic())
                    .longUnitNumber(sysBizGoodsSku.getLongUnitNumber())
                    .specsKey(sysBizGoodsSku.getSpecsKey())
                    .specsName(sysBizGoodsSku.getSpecsData())
                    .totalPrice(totalAmount)
                    .unitPrice(price)
                    .marketPrice(marketPrice).build());
        }

        String uniqueId = StringUtils.leftPad(userId.toString(), 8, "0") + time;
        String orderId = OrderNoCreate.activityOrderCode(OrderTypeEnum.GOODS.name());
        String payId = "PAY" + uniqueId;
        // 真实支付金额
        BigDecimal amountPay = amount;
        // 优惠券扣除
        SysBizCouponReceive sysBizCouponReceive = null;
        if (orderPerDto.getCouponId() != null) {
            sysBizCouponReceive = sysBizCouponReceiveService.getById(orderPerDto.getCouponId());
            if (sysBizCouponReceive == null) {
                return "优惠券不存在";
            }
            if (sysBizCouponReceive.getStatus() == 1) {
                return "优惠券已使用";
            }
            if (sysBizCouponReceive.getStatus() == 2) {
                return "优惠券已过期";
            }
            if (sysBizCouponReceive.getTermBeginTime().compareTo(new Date()) > 0) {
                return "优惠券未到使用时间";
            }
            if (!Objects.equals(sysBizCouponReceive.getUserId(), userId)) {
                return "优惠券不属于该用户";
            }
            if (sysBizCouponReceive.getThresholdAmount().compareTo(BigDecimal.ZERO) != 0 && sysBizCouponReceive.getThresholdAmount().compareTo(amount) > 0) {
                return "优惠券不满足使用条件";
            }
            amountPay = amountPay.subtract(sysBizCouponReceive.getDiscountValue());
            sysBizOrder.setUserCouponId(sysBizCouponReceive.getId());
            sysBizOrder.setCouponName(sysBizCouponReceive.getCouponName());
            sysBizOrder.setCouponPrice(sysBizCouponReceive.getDiscountValue());
            sysBizCouponReceive.setStatus(ReceiveStatusEnum.USED.getKey());
        }
        if (amountPay.compareTo(BigDecimal.ZERO) > 0) {
            if (orderPerDto.getIsBalanceDiscount() != null && orderPerDto.getIsBalanceDiscount()) {

            }
            if (orderPerDto.getIsSurplus() != null && orderPerDto.getIsSurplus()) {
                if (sysBizUser.getSurplus().compareTo(BigDecimal.ZERO) == 0) {
                    return "余额不足";
                }
                if (amountPay.compareTo(BigDecimal.ZERO) > 0) {
                    if (sysBizUser.getSurplus().compareTo(amountPay) >= 0) {
                        sysBizOrder.setSurplusAmount(amountPay);
                        // 纯余额支付
                        amountPay = BigDecimal.ZERO;
                    }

                }
            }
        }
        sysBizOrder.setActualPaymentAmount(amountPay);
        sysBizOrder.setAmount(amount);
        sysBizOrder.setTotalPrice(amount);
        sysBizOrder.setFuyouDiscountAmount(amountPay);
        sysBizOrder.setPayableAmount(amount);
        sysBizOrder.setPhone(sysBizUser.getUserPhone());
        sysBizOrder.setPaymentTime(nowDate);
        sysBizOrder.setPaymentId(payId);
        sysBizOrder.setStatus(10);
        sysBizOrder.setOrderCode(orderId);
        sysBizOrder.setPaymentStatus(0);
        sysBizOrder.setOrderAddTime(nowDate);
        sysBizOrder.setPaymentTimeEnd(DateUtils.addMinutes(nowDate, 15));
        sysBizOrderMapper.insert(sysBizOrder);
        for (SysBizOrderGoods sysBizOrderGoods : sysBizOrderGoodsList) {
            sysBizOrderGoods.setOrderId(sysBizOrder.getId());
        }

        if (sysBizCouponReceive != null) {
            if (sysBizCouponReceive.getScopeUse() == 1) {
                // 全场通用优惠券：按商品金额比例分配
                distributeDiscountByAmount(sysBizOrderGoodsList, sysBizCouponReceive.getDiscountValue());
            } else if (sysBizCouponReceive.getScopeUse() == 2) {
                // 指定商品优惠券：按商品金额比例分配

                // 查询指定优惠券适用的商品列表
                List<SysBizCouponGoods> sysBizCouponGoods = sysBizCouponGoodsMapper.selectList(
                        new LambdaQueryWrapper<SysBizCouponGoods>()
                                .eq(SysBizCouponGoods::getCouponId, sysBizCouponReceive.getId())
                );


                // 将订单中的商品列表转换为 Map，键为商品 ID，值为商品对象
                Map<Long, SysBizOrderGoods> orderGoodsMap = sysBizOrderGoodsList.stream()
                        .collect(Collectors.toMap(SysBizOrderGoods::getGoodsId, Function.identity()));

                // 筛选出当前优惠券适用的商品
                List<SysBizOrderGoods> matchedGoods = sysBizCouponGoods.stream()
                        .map(SysBizCouponGoods::getGoodsId)
                        .filter(orderGoodsMap::containsKey)
                        .map(orderGoodsMap::get)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                // 按照商品金额比例分配优惠券金额
                distributeDiscountByAmount(matchedGoods, sysBizCouponReceive.getDiscountValue());

                // 如果存在匹配的商品，则将分配的优惠金额设置到订单商品中
                if (!CollectionUtils.isEmpty(matchedGoods)) {
                    // 遍历订单商品列表
                    for (SysBizOrderGoods sysBizOrderGoods : sysBizOrderGoodsList) {
                        // 遍历匹配的商品列表
                        for (SysBizOrderGoods matchedGood : matchedGoods) {
                            // 如果商品 ID 匹配
                            if (matchedGood.getId().equals(sysBizOrderGoods.getId())) {
                                // 设置优惠金额
                                sysBizOrderGoods.setCouponPrice(matchedGood.getCouponPrice());
                            }
                        }
                    }
                }
            }
        }


        sysBizOrderGoodsService.saveBatch(sysBizOrderGoodsList);
        if (sysBizOrder.getSurplusAmount() != null && sysBizOrder.getSurplusAmount().compareTo(BigDecimal.ZERO) > 0) {
            sysBizUser.setSurplus(sysBizUser.getSurplus().subtract(sysBizOrder.getSurplusAmount()));
            if (sysBizOrder.getFuyouDiscountAmount() == null || sysBizOrder.getFuyouDiscountAmount().compareTo(BigDecimal.ZERO) == 0) {
                sysBizUserSurplusDetailsService.save(SysBizUserSurplusDetails.builder().userId(sysBizOrder.getUserId()).type(1).orderId(sysBizOrder.getOrderCode()).createTime(DateUtils.getNowDate()).price(sysBizOrder.getSurplusAmount()).rechargePrice(sysBizOrder.getSurplusAmount()).build());
            }
        }

        sysBizUserService.updateById(sysBizUser);
        if (sysBizCouponReceive != null) {
            sysBizCouponReceiveService.updateById(sysBizCouponReceive);
        }
        // 将数据存入redisson队列
        String key = "ORDER_" + payId;
        delayedQueue.offerAsync(key, 15, TimeUnit.MINUTES);
        return StringUtils.EMPTY;
    }


    /**
     * 按比例分配优惠金额，确保用户无法通过退单薅羊毛
     *
     * @param goodsList 商品列表
     * @param discountValue 优惠券金额
     */
    public static void distributeDiscountByAmount(List<SysBizOrderGoods> goodsList, BigDecimal discountValue) {
        // 计算商品的总金额
        BigDecimal totalAmount = BigDecimal.ZERO;

        for (SysBizOrderGoods goods : goodsList) {
            BigDecimal goodsPrice = goods.getTotalPrice();
            if (goodsPrice == null || goodsPrice.compareTo(BigDecimal.ZERO) <= 0) {
                throw new IllegalArgumentException("商品价格无效: " + goodsPrice);
            }
            totalAmount = totalAmount.add(goodsPrice);
        }

        if (totalAmount.compareTo(BigDecimal.ZERO) == 0) {
            throw new IllegalStateException("商品总金额为 0，无法分配优惠券折扣");
        }

        // 校验：优惠金额不能超过总金额
        if (discountValue.compareTo(totalAmount) > 0) {
            throw new IllegalStateException("优惠金额超出商品总金额，可能存在薅羊毛风险");
        }

        // 剩余未分配的优惠金额
        BigDecimal remainingDiscount = discountValue;

        for (int i = 0; i < goodsList.size(); i++) {
            SysBizOrderGoods goods = goodsList.get(i);
            BigDecimal goodsPrice = goods.getTotalPrice();

            // 按比例分配优惠金额
            BigDecimal itemDiscount = goodsPrice.multiply(discountValue).divide(totalAmount, 6, RoundingMode.HALF_UP); // 中间计算保留 6 位小数

            // 最后一个商品分配剩余的优惠金额
            if (i == goodsList.size() - 1) {
                itemDiscount = remainingDiscount;
            } else {
                remainingDiscount = remainingDiscount.subtract(itemDiscount);
            }

            // 设置商品的优惠金额，保留两位小数
            goods.setCouponPrice(itemDiscount.setScale(2, RoundingMode.HALF_UP));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void balanceDiscount(SysBizOrder sysBizOrder) {
        // 使用UpdateWrapper明确指定更新字段，避免触发自动填充
        LambdaUpdateWrapper<SysBizOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysBizOrder::getId, sysBizOrder.getId())
                .set(SysBizOrder::getStatus, 15)
                .set(SysBizOrder::getPaymentStatus, 1)
                .set(SysBizOrder::getPaymentTime, DateUtils.getNowDate())
                .set(SysBizOrder::getPaymentType, 2);

        sysBizOrderMapper.update(null, updateWrapper);

        // 更新用户余额
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(sysBizOrder.getUserId());
        if (sysBizUser == null) {
            throw new ServiceException("用户不存在");
        }
        if (sysBizOrder.getActualPaymentAmount() != null && sysBizUser.getSurplus().compareTo(sysBizOrder.getActualPaymentAmount()) < 0) {
            throw new ServiceException("余额不足");
        } else if (sysBizOrder.getActualPaymentAmount() != null && sysBizUser.getSurplus().compareTo(sysBizOrder.getActualPaymentAmount()) >= 0) {
            sysBizUser.setSurplus(sysBizUser.getSurplus().subtract(sysBizOrder.getActualPaymentAmount()));

            // 余额消费记录到 流水明细表
            sysBizUserSurplusDetailsService.save(SysBizUserSurplusDetails.builder()
                    .userId(sysBizOrder.getUserId())
                    .tenantId(sysBizOrder.getTenantId())
                    .type(1)
                    .orderId(sysBizOrder.getOrderCode())
                    .createTime(DateUtils.getNowDate())
                    .price(sysBizOrder.getActualPaymentAmount())
                    .rechargePrice(BigDecimal.ZERO)
                    .build());
        }

        // 新余额消费记录
        sysBizUserService.updateById(sysBizUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelOrder(SysBizOrder sysBizOrder) {

        // 第三方 对接
        if (sysBizOrder.getStatus() == 20) {
            try {
                // 时间戳
                String timeStamp = String.valueOf(System.currentTimeMillis());

                ReceiveHyOrderCancelDto receiveHyOrderCancelDto = new ReceiveHyOrderCancelDto();
                receiveHyOrderCancelDto.setOrderCode(sysBizOrder.getOrderCode());
                receiveHyOrderCancelDto.setCancelTime(DateUtils.getNowDate());
                receiveHyOrderCancelDto.setCancelCause(sysBizOrder.getCancelReason());

                // 签名（假设使用 SHA-256 对 data 和 timeStamp 进行签名）
                String sign = SignatureUtils.signWithSHA1(JSON.toJSONString(receiveHyOrderCancelDto), SignatureUtils.getPrivateKey(privateKey));

                // 请求体
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("timeStamp", timeStamp);
                requestBody.put("sign", sign);
                requestBody.put("data", JSON.toJSONString(receiveHyOrderCancelDto));

                // 发送 POST 请求
                String response = HttpUtil.postJson(cancelUrl, JSON.toJSONString(requestBody));
                log.info("订单推送:{}", response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

//        Date nowDate = DateUtils.getNowDate();
//        sysBizOrder.setCancelTime(nowDate);
//        sysBizOrder.setCancelReason("取消订单");
//        sysBizOrder.setUpdateTime(nowDate);
//        sysBizOrder.setStatus(90);

        Date nowDate = DateUtils.getNowDate();
        LambdaUpdateWrapper<SysBizOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysBizOrder::getId, sysBizOrder.getId())
                .set(SysBizOrder::getStatus, 90)
                .set(SysBizOrder::getUpdateTime, nowDate)
                .set(SysBizOrder::getCancelTime, nowDate)
                .set(SysBizOrder::getCancelReason, "取消订单");

        int i = sysBizOrderMapper.update(null, updateWrapper);
        log.info("--- cancelOrder 取消订单:{}", i);

        // 释放库存和销量
        List<SysBizOrderGoods> sysBizOrderGoodsList = sysBizOrderGoodsService.selectSysBizOrderGoodsList(new LambdaQueryWrapper<SysBizOrderGoods>().eq(SysBizOrderGoods::getOrderId, sysBizOrder.getId()));
        for (SysBizOrderGoods sysBizOrderGoods : sysBizOrderGoodsList) {
            SysBizGoods sysBizGoods = sysBizGoodsService.selectSysBizGoodsById(sysBizOrderGoods.getGoodsId());
            sysBizGoodsService.update(new LambdaUpdateWrapper<SysBizGoods>()
                    .set(SysBizGoods::getRealitySales,
                            Math.max(0, sysBizGoods.getRealitySales() - sysBizOrderGoods.getNumber()))// 防止释放库存产生负数的情况
                    .eq(SysBizGoods::getId, sysBizGoods.getId()));
            // 这个地方要改成 sys_biz_goods 表 释放库存
            sysBizGoodsService.releaseStocks(sysBizGoods.getId(), sysBizOrderGoods.getNumber());
        }
        // 是否使用优惠券
        if (sysBizOrder.getUserCouponId() != null) {
            // 优惠券使用状态修改
            log.info("修改优惠券状态{}", sysBizOrder.getUserCouponId());
            SysBizCouponReceive sysBizCouponReceive = sysBizCouponReceiveService.selectSysBizCouponReceiveById(sysBizOrder.getUserCouponId());
            sysBizCouponReceive.setStatus(ReceiveStatusEnum.UNUSED.getKey());
            sysBizCouponReceiveService.updateById(sysBizCouponReceive);
        }

        // 根据支付方式进行退款操作 (0：微信  1：支付宝  2：余额)
        Integer paymentType = sysBizOrder.getPaymentType();
        if (paymentType == 0) {
            String refundId = "R" + System.currentTimeMillis();
            Boolean refund = payService.refund(refundId, sysBizOrder);
            log.info("---- 微信退款状态：refund:{}", refund);
            if (refund) {
                userSurplus(sysBizOrder);
            }
        } else if (paymentType == 1) {
            String zfbStr = alipayService.refund(sysBizOrder.getTenantId(), sysBizOrder.getOrderCode(), sysBizOrder.getActualPaymentAmount().doubleValue(), "订单取消退款", sysBizOrder.getTransactionId());
            log.info("---- zfbStr状态：zfbStr:{}", zfbStr);
            if ("订单退款成功".equals(zfbStr)) {
                userSurplus(sysBizOrder);
            }
        } else if (paymentType == 2) {
            SysBizUser sysBizUser = sysBizUserService.getById(sysBizOrder.getUserId());
            sysBizUserService.update(new LambdaUpdateWrapper<SysBizUser>()
                    .set(SysBizUser::getSurplus, sysBizUser.getSurplus().add(sysBizOrder.getActualPaymentAmount()))
                    .eq(SysBizUser::getId, sysBizOrder.getUserId()));
            // 余额消费记录到 流水明细表
            userSurplus(sysBizOrder);
        }
    }

    private void userSurplus(SysBizOrder sysBizOrder) {
        // 余额消费记录到 流水明细表
        sysBizUserSurplusDetailsService.save(SysBizUserSurplusDetails.builder()
                .userId(sysBizOrder.getUserId())
                .tenantId(sysBizOrder.getTenantId())
                .type(0)
                .orderId(sysBizOrder.getOrderCode())
                .createTime(DateUtils.getNowDate())
                .price(sysBizOrder.getActualPaymentAmount())
                .rechargePrice(BigDecimal.ZERO)
                .build());
    }

    @Override
    public OrderDetailVo queryOrderDetail(SysBizOrder sysBizOrder) {
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        BeanUtils.copyProperties(sysBizOrder, orderDetailVo);
        orderDetailVo.setTotalAmount(sysBizOrder.getAmount());
        orderDetailVo.setAmount(sysBizOrder.getFuyouDiscountAmount());
        orderDetailVo.setReceiverAddress(sysBizOrder.getReceiverAddress());
        List<OrderGoodsVo> orderGoodsVoList = new ArrayList<>();
        List<SysBizOrderGoods> sysBizOrderGoodsList = sysBizOrderGoodsService.selectSysBizOrderGoodsList(new LambdaQueryWrapper<SysBizOrderGoods>().eq(SysBizOrderGoods::getOrderId, sysBizOrder.getId()));
        for (SysBizOrderGoods sysBizOrderGoods : sysBizOrderGoodsList) {
//            SysBizGoodsSku sysBizGoodsSku = sysBizGoodsSkuService.getOne(new LambdaQueryWrapper<SysBizGoodsSku>().eq(SysBizGoodsSku::getGoodsId,
//                    sysBizOrderGoods.getGoodsId()).eq(SysBizGoodsSku::getSpecsKey, sysBizOrderGoods.getSpecsKey()));
            orderGoodsVoList.add(OrderGoodsVo.builder().goodsName(sysBizOrderGoods.getGoodsName()).cover(sysBizOrderGoods.getSkuPic()).skuId(sysBizOrderGoods.getSkuId()).id(sysBizOrderGoods.getGoodsId()).number(sysBizOrderGoods.getNumber()).marketPrice(sysBizOrderGoods.getMarketPrice()).salesPrice(sysBizOrderGoods.getUnitPrice()).specsKey(sysBizOrderGoods.getSpecsKey()).build());
        }
        orderDetailVo.setOrderGoodsVoList(orderGoodsVoList);
        // 查询售后信息
        SysBizOrderService orderService = sysBizOrderServiceService.getOne(new LambdaQueryWrapper<SysBizOrderService>()
                .eq(SysBizOrderService::getOrderId, sysBizOrder.getId()));
        if (orderService != null) {
            AfterServiceVo afterServiceVo = new AfterServiceVo();
            afterServiceVo.setGoodsInfo(orderService.getGoodsInfo());
            afterServiceVo.setRefundTime(orderService.getRefundTime());
            afterServiceVo.setApplyReason(orderService.getApplyReason());
            afterServiceVo.setVoucherImages(orderService.getVoucherImages());
            afterServiceVo.setRefundNo(orderService.getRefundNo());
            afterServiceVo.setRefundAmount(orderService.getRefundAmount());
            afterServiceVo.setAuditTime(orderService.getAuditTime());
            afterServiceVo.setAuditReason(orderService.getAuditReason());
            afterServiceVo.setApplyTime(orderService.getApplyTime());
            afterServiceVo.setReturnReason(orderService.getReturnReason());
            orderDetailVo.setAfterServiceVo(afterServiceVo);
        }
        return orderDetailVo;
    }

    @Override
    public List<SysBizOrder> queryDevelopMemberOrder(List<Long> userIdList) {
        LambdaQueryWrapper<SysBizOrder> sysBizOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizOrderLambdaQueryWrapper.in(SysBizOrder::getUserId, userIdList);
        sysBizOrderLambdaQueryWrapper.eq(SysBizOrder::getPaymentStatus, 1);
        sysBizOrderLambdaQueryWrapper.eq(SysBizOrder::getDelStatus, OrderDeleteEnum.NOT_DELETE.getKey());
        sysBizOrderLambdaQueryWrapper.orderByDesc(SysBizOrder::getId);
        List<SysBizOrder> sysBizOrders = sysBizOrderMapper.selectList(sysBizOrderLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(sysBizOrders)) {
            for (SysBizOrder sysBizOrder : sysBizOrders) {
                SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(sysBizOrder.getUserId());
                sysBizOrder.setUserName(sysBizUser.getNickName());
                sysBizOrder.setPhone(sysBizUser.getUserPhone());
                sysBizOrder.setAvatar(sysBizUser.getAvatar());
            }
        }
        return sysBizOrders;
    }

    /**
     * 批量发货
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int orderImportData(List<SysBizOrderImport> orderImports, boolean updateSupport, String operName) {
        int failureNum = 0;
        if (StringUtils.isNull(orderImports) || orderImports.isEmpty() || orderImports.stream().allMatch(Objects::isNull)) {
            failureNum = -1;
            return failureNum;
        }
        for (SysBizOrderImport orderImport : orderImports) {
            SysBizImportFail sysBizImportFail = new SysBizImportFail();
            LoginUser loginUser = SecurityUtils.getLoginUser();
            sysBizImportFail.setUserId(loginUser.getUserId());
            sysBizImportFail.setType(ImportFailEnum.ORDER_SHIPPING.getKey());
            sysBizImportFail.setOrderCode(orderImport.getOrderCode());
            if (orderImport.getOrderCode().isEmpty() || orderImport.getOrderCode().trim().length() > 15) {
                sysBizImportFail.setFailureReason("订单编号不能为空或长度不能超过15");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }

            LambdaQueryWrapper<SysBizOrder> SysBizOrderWrapper = new LambdaQueryWrapper<SysBizOrder>();
            SysBizOrderWrapper.eq(SysBizOrder::getOrderCode, orderImport.getOrderCode().trim());
            SysBizOrder sysBizOrder = sysBizOrderMapper.selectOne(SysBizOrderWrapper);
            // 验证编号是否存在
            if (sysBizOrder == null || sysBizOrder.getOrderCode().isEmpty()) {
                failureNum++;
                sysBizImportFail.setFailureReason("订单编号不存在");
                sysBizImportFailMapper.insert(sysBizImportFail);
            } else if (sysBizOrder.getStatus() == 10) {
                failureNum++;
                sysBizImportFail.setFailureReason("订单未付款");
                sysBizImportFailMapper.insert(sysBizImportFail);
            } else if (sysBizOrder.getStatus() > 20 && sysBizOrder.getStatus() < 60) {
                failureNum++;
                sysBizImportFail.setFailureReason("订单已发货");
                sysBizImportFailMapper.insert(sysBizImportFail);
            } else if (sysBizOrder.getStatus() == 60) {
                failureNum++;
                sysBizImportFail.setFailureReason("订单已关闭");
                sysBizImportFailMapper.insert(sysBizImportFail);
            } else {
                sysBizOrder.setUpdateTime(DateUtils.getNowDate());
                sysBizOrder.setStatus(OrderSatusEnum.TO_BE_RECEIVED.getKey());
                try {
                    updateSysBizOrder(sysBizOrder);
                } catch (Exception e) {
                    sysBizImportFail.setFailureReason("数据格式错误");
                    sysBizImportFailMapper.insert(sysBizImportFail);
                    failureNum++;
                }
            }
        }
        return failureNum;

    }

    //导出
    @Override
    public List<SysBizOrderExportVo> selectSysBizOrderExportList(SysBizOrder sysBizOrder) {
        return sysBizOrderMapper.selectSysBizOrderExportList(sysBizOrder);
    }

    @Override
    public List<OrderCodeVo> listOrderCode() {
        return sysBizOrderMapper.listOrderCode();
    }

    @Override
    public List<OrderCodeVo> listReceiver() {
        return sysBizOrderMapper.listReceiver();
    }

    @Override
    public List<OrderCodeVo> listContactNumber() {
        return sysBizOrderMapper.listContactNumber();
    }

    @Override
    public String orderPush(Long id) {
        SysBizOrder sysBizOrder = sysBizOrderMapper.selectById(id);
        if (sysBizOrder.getStatus() != 15) {
            return "订单状态已修改，请刷新";
        }
        sysBizOrder.setReceiverAddress(sysBizOrder.getProvince() + sysBizOrder.getCity() + sysBizOrder.getArea() + sysBizOrder.getStreet() + sysBizOrder.getHouseNum());
        SysBizOrderGoods sysBizOrderGoods = new SysBizOrderGoods();
        sysBizOrderGoods.setOrderId(id);
        List<SysBizOrderGoods> sysBizOrderGoodsList = sysBizOrderGoodsService.selectSysBizOrderGoodsList(sysBizOrderGoods);
        if (sysBizOrderGoodsList != null) {
            for (SysBizOrderGoods bizOrderGoods : sysBizOrderGoodsList) {
                bizOrderGoods.setSpecsName(bizOrderGoods.getSpecsKey());
            }
        }
        sysBizOrder.setSysBizOrderGoodsList(sysBizOrderGoodsList);


        ReceiveHyOrderDto receiveHyOrderDto = new ReceiveHyOrderDto();
        receiveHyOrderDto.setId(sysBizOrder.getId()); // 订单id
        receiveHyOrderDto.setOrderCode(sysBizOrder.getOrderCode());// 订单编号
        receiveHyOrderDto.setStatus(sysBizOrder.getStatus());  // 订单状态
        receiveHyOrderDto.setUserId(sysBizOrder.getUserId());  // 下单人id
//        receiveHyOrderDto.setBelongShopId(sysBizOrder.getBelongShopId());  // 归属店铺id
//        receiveHyOrderDto.setBelongDealerId(sysBizOrder.getBelongDealerId()); // 归属经销商id


        receiveHyOrderDto.setBelongShopId(0L);  // 先传0
        receiveHyOrderDto.setBelongDealerId(0L); // 先传0

        //receiveHyProductsDto
        List<SysBizShopCertification> sysBizShopCertifications = sysBizShopCertificationMapper.selectList(
                new LambdaQueryWrapper<SysBizShopCertification>()
                        .eq(SysBizShopCertification::getUserId, sysBizOrder.getUserId())
                        .eq(SysBizShopCertification::getTenantId, sysBizOrder.getTenantId())
                        .eq(SysBizShopCertification::getDeleted, 0)
                        .eq(SysBizShopCertification::getCertificationStatus, 3)
                        .last("limit 1")
        );
        if (!CollectionUtils.isEmpty(sysBizShopCertifications)) {
            receiveHyOrderDto.setUserName(sysBizShopCertifications.get(0).getShopName());
        } else {
            receiveHyOrderDto.setUserName(sysBizOrder.getUserName()); // 下单人
        }
        receiveHyOrderDto.setTenantId(sysBizOrder.getTenantId()); //站点Id
        receiveHyOrderDto.setPhone(sysBizOrder.getPhone());// 下单人手机号
        receiveHyOrderDto.setAmount(sysBizOrder.getAmount());// 订单金额
        receiveHyOrderDto.setPayableAmount(sysBizOrder.getPayableAmount());// 应付金额
        receiveHyOrderDto.setActualPaymentAmount(sysBizOrder.getActualPaymentAmount());// 实付金额
        receiveHyOrderDto.setTotalPrice(sysBizOrder.getTotalPrice());// 总计
        receiveHyOrderDto.setPaymentStatus(sysBizOrder.getPaymentStatus());// 支付状态
        receiveHyOrderDto.setPaymentNo(sysBizOrder.getPaymentNo());// 支付流水号
        receiveHyOrderDto.setPaymentTime(sysBizOrder.getPaymentTime()); // 支付时间
        receiveHyOrderDto.setReceiver(sysBizOrder.getReceiver()); // 收货人
        receiveHyOrderDto.setAddressId(sysBizOrder.getAddressId());
        receiveHyOrderDto.setContactNumber(sysBizOrder.getContactNumber()); // 收货人联系电话
        receiveHyOrderDto.setReceiverAddress(sysBizOrder.getReceiverAddress()); // 收货地址
        receiveHyOrderDto.setOrderAddTime(sysBizOrder.getOrderAddTime()); // 下单时间
        receiveHyOrderDto.setProvince(sysBizOrder.getProvince()); // 省
        receiveHyOrderDto.setCity(sysBizOrder.getCity()); // 市
        receiveHyOrderDto.setArea(sysBizOrder.getArea()); // 区
        receiveHyOrderDto.setStreet(sysBizOrder.getStreet()); // 街道 (街道数据需统一，平台端后续会提供）)
        receiveHyOrderDto.setLongitude(sysBizOrder.getLng()); // 收货地址经度
        receiveHyOrderDto.setLatitude(sysBizOrder.getLat()); // 收货地址纬度
        receiveHyOrderDto.setRemark(sysBizOrder.getRemark()); // 备注
        receiveHyOrderDto.setCouponPrice(sysBizOrder.getCouponPrice()); // 优惠券金额
        receiveHyOrderDto.setTransactionId(sysBizOrder.getTransactionId()); // 微信流水号

        List<ReceiveHyProductsDto> receiveHyProductsDtos = new ArrayList<ReceiveHyProductsDto>();
        if (!CollectionUtils.isEmpty(sysBizOrder.getSysBizOrderGoodsList())) {
            for (SysBizOrderGoods bizOrderGoods : sysBizOrder.getSysBizOrderGoodsList()) {
                ReceiveHyProductsDto receiveHyProductsDto = new ReceiveHyProductsDto();
                receiveHyProductsDto.setId(bizOrderGoods.getId());
                receiveHyProductsDto.setOrderId(String.valueOf(bizOrderGoods.getOrderId()));
                receiveHyProductsDto.setGoodsId(bizOrderGoods.getGoodsId());

                //手动推送时 要去查一下当前商品最新的code
                SysBizGoodsSku sysBizGoodsSku = sysBizGoodsSkuService.selectSysBizGoodsSkuById(bizOrderGoods.getSkuId());
                if(sysBizGoodsSku!=null){
                    receiveHyProductsDto.setProductCode(sysBizGoodsSku.getErpProductCode());
                }else{
                    receiveHyProductsDto.setProductCode(bizOrderGoods.getErpProductCode());
                }
//                receiveHyProductsDto.setLongUnitNumber(bizOrderGoods.getLongUnitNumber());
                receiveHyProductsDto.setGoodsName(bizOrderGoods.getGoodsName());
                receiveHyProductsDto.setUnitPrice(bizOrderGoods.getUnitPrice());
                receiveHyProductsDto.setTotalPrice(bizOrderGoods.getTotalPrice());
//                receiveHyProductsDto.setNumber(Integer.parseInt(String.valueOf(bizOrderGoods.getNumber())) * bizOrderGoods.getLongUnitNumber());
//                receiveHyProductsDto.setNumber(Integer.parseInt(String.valueOf(bizOrderGoods.getNumber())));
                if(bizOrderGoods.getErpSmallUnit()==1){
                    receiveHyProductsDto.setNumber(Integer.parseInt(String.valueOf(bizOrderGoods.getNumber())) * bizOrderGoods.getLongUnitNumber());
                }else{
                    receiveHyProductsDto.setNumber(Integer.parseInt(String.valueOf(bizOrderGoods.getNumber())));
                }
                receiveHyProductsDtos.add(receiveHyProductsDto);
            }

        }
        receiveHyOrderDto.setProducts(receiveHyProductsDtos); // 订单商品集合


        try {
            // 订单信息

            // 时间戳
            String timeStamp = String.valueOf(System.currentTimeMillis());

            // 签名（假设使用 SHA-256 对 data 和 timeStamp 进行签名）
            String sign = SignatureUtils.signWithSHA1(JSON.toJSONString(receiveHyOrderDto), SignatureUtils.getPrivateKey(privateKey));

            // 请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("timeStamp", timeStamp);
            requestBody.put("sign", sign);
            requestBody.put("data", JSON.toJSONString(receiveHyOrderDto));
            log.info("请求体:{}", JSON.toJSONString(receiveHyOrderDto));

            // 发送 POST 请求
            String response = HttpUtil.postJson(url, JSON.toJSONString(requestBody));
            log.info("订单推送------------:{}", response);
            // 解析响应
            JSONObject jsonResponse = JSON.parseObject(response);
            int code = jsonResponse.getIntValue("code");

            log.info("返回值------------:{}", jsonResponse);
            // 检查 code 字段
            if (code == 200) {
                sysBizOrder.setStatus(20);
                sysBizOrderMapper.updateSysBizOrder(sysBizOrder);
                return "推送成功";
            } else {
                LambdaUpdateWrapper<SysBizOrder> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(SysBizOrder::getId, sysBizOrder.getId())
                        .setSql("push_num = push_num + 1");
                sysBizOrderMapper.update(null, updateWrapper);
                // 处理其他情况
                return "推送失败";
            }


        } catch (Exception e) {
            LambdaUpdateWrapper<SysBizOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SysBizOrder::getId, sysBizOrder.getId())
                    .setSql("push_num = push_num + 1");
            sysBizOrderMapper.update(null, updateWrapper);
            e.printStackTrace();
        }
        return "推送失败";
    }


}
